package com.wyh.yuhcloud.service.impl;



import com.wyh.yuhcloud.dao.UserMapper;
import com.wyh.yuhcloud.dto.AddUserDto;
import com.wyh.yuhcloud.dto.LoginUserDto;
import com.wyh.yuhcloud.dto.ResultDto;
import com.wyh.yuhcloud.entity.User;
import com.wyh.yuhcloud.service.UserService;
import com.wyh.yuhcloud.util.DefaultPasswordEncoder;
import com.wyh.yuhcloud.util.DiyIDUtils;
import com.wyh.yuhcloud.util.EncrUtil;
import com.wyh.yuhcloud.util.RedisUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;


import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.math.BigInteger;
import java.security.MessageDigest;


@Service
public class UserServiceImpl implements UserService {
    private final Logger log = LoggerFactory.getLogger(UserServiceImpl.class);

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private JavaMailSenderImpl javaMailSender;

    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private EncrUtil encrUtil;


    /**
     * 注册用户
     * @param addUserDto 添加数据流
     * @return 成功
     */
    @Override
    public String signUp(AddUserDto addUserDto) {

        if (redisUtils.hasKey(addUserDto.getUserEmail())){
            if (addUserDto.getMailCheck().equals(redisUtils.get(addUserDto.getUserEmail()))){
                User user = new User();
                //String uuid = UUID.randomUUID().toString();
                String id = new DiyIDUtils("YH",1).nextId();
                user.setUserId(id);
                user.setUserName(addUserDto.getUserName());
                user.setUserPassword(new DefaultPasswordEncoder().encode(addUserDto.getUserPassword()));
                user.setVersion(3);
                user.setIslock(0);
                user.setUserEmail(addUserDto.getUserEmail());
                userMapper.signUp(user);
                log.info("业务层注册--"+id);
                return "注册成功！";
            }
        }

        return "注册失败！请检查验证码~";

    }

    @Override
    public ResultDto userLogin(LoginUserDto loginUserDto) {
        return null;
    }

    /**
     * hash的Md5方式加密
     * @param pwd 密码
     * @return 加密后密码
     */
    private String hashMd5(String pwd) {
        try {
            //生成加密计算器
            MessageDigest md = MessageDigest.getInstance("MD5");
            //计算md5函数
            md.update(pwd.getBytes());
            // digest()最后确定返回md5 hash值，返回值为8位字符串。因为md5 hash值是16位的hex值，实际上就是8位
            // BigInteger函数则将8位的字符串转换成16位hex值，用字符串来表示﹔得到字符串形式的hash值
            //一个byte是八位二进制，也就是2位十六进制字符（2的8次方等于16的2次方)
            return new BigInteger(1,md.digest()).toString();
        } catch (Exception e) {
            throw new RuntimeException("加密失败");
        }
    }


    /**
     * 获取等级存入redis
     * @param userName
     * @return
     */
    @Override
    public Integer queryVersion(String userName) {
        //userName = encrUtil.decrypt(userName);
        if (redisUtils.hasKey(userName)){
            return (Integer) redisUtils.get(userName);
        }else {
            Integer version = userMapper.queryVersion(userName);
            redisUtils.set(userName,version);
            redisUtils.expire(userName,604800);
            return version;
        }

    }

    /**
     * 发送验证码
     * @param mail 目标邮箱
     */
    @Override
    public void mailCheck(String mail){
        //创建复杂邮件
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        //组装
        MimeMessageHelper helper = null;
        try {
            helper = new MimeMessageHelper(mimeMessage,true);
            //正文
            helper.setSubject("注册验证码");
            String check = new DiyIDUtils("YZM",1).nextId();
            helper.setText("<h3>验证码为： "+check+"</h3>",true);
            //发送方接受方
            helper.setTo(mail);
            helper.setFrom("3355796274@qq.com");
            javaMailSender.send(mimeMessage);
            redisUtils.set(mail,check);
            redisUtils.expire(mail,60);
        } catch (MessagingException e) {
            e.printStackTrace();
        }

    }

    @Override
    public User selectByUsername(String username) {
        return userMapper.userInfo(username);
    }

    @Override
    public Integer selectPermissionValueByUserId(String id) {

        if (redisUtils.hasKey(id)){
            return (Integer) redisUtils.get(id);
        }else {
            Integer version = userMapper.queryVersionById(id);
            redisUtils.set(id,version);
            redisUtils.expire(id,604800);
            return version;
        }

    }
}
